﻿var Database = require('../app/database');
var util = require('util');
var fs = require('fs');
var path = require('path');
var mu = require('mu2');

var TemplateBuilder = module.exports = {};

log = function(msg) {
    console.log(new Date().toLocaleTimeString() + ' [template_builder]: ' + msg);
};

TemplateBuilder.Status = false;

var buildTemplate = function(values, destination, template) {
    log('Template Root: ' + mu.root + ' | destination: ' + destination + ' | values: ' + values.length);
    var outputStream = fs.createWriteStream(destination, { flags: 'w' });
    outputStream.on('close', function () {
        log('All written!');
    });
    log('start rendering: ' + template.get('file'));
    var stream = mu.compileAndRender(template.get('file'), values)
        .on('end', function () {
            log('done rendering: ' + template.get('file'));
        })
        .on('error', function(err) {
            log('error rendering: ' + util.inspect(err,false,null));
            outputStream.end(util.inspect(err,false,null));
        })
        .pipe(outputStream);
};

TemplateBuilder.execute = function(server_id) {
    return new Database.Models.Server({server_id: server_id})
    .fetch({withRelated: ['configs','templates','memberrights','memberrights.member']})
    .then(function(resp){
            if (resp != null){
                var server = resp;
                if (server.related('templates') != null) {
                    var values = {};

                    if (server.related('configs') != null) {
                        for (var i = 0; i < server.related('configs').length; i++) {
                            var config = server.related('configs').at(i);
                            values[config.get('name')] = config.get('value');
                        };
                    };
                    var keys = Object.keys(server.attributes);
                    for (var i = 0; i < keys.length; i++) {
                        var attribute = keys[i];
                        if (attribute != 'configs' && attribute != 'templates') {
                            values['server_' + attribute] = server.get(attribute);
                        };
                    };
                    if (server.related('memberrights') != null) {
                        values['members'] = [];
                        for (var i = 0; i < server.related('memberrights').length; i++) {
                            var memberright = server.related('memberrights').at(i);
                            var rank = memberright.related('member').get('member_rank');
                            if (!rank || rank.length <= 0) {
                                rank = "RECRUIT";
                            };
                            var member = {
                                'gameid': memberright.related('member').get('game_id'),
                                'rights': [],
                                'name': memberright.related('member').get('member_name'),
                                'rank': rank.toString().trim().toUpperCase()
                            };
                            if (member.gameid && member.gameid.length > 0) {
                                var rights_list = memberright.get('rights_list').toString().toLowerCase().replace("\"","").replace("'","").replace(" ","").replace(";",",").replace("|",",").split(",");
                                for (var j = 0; j < rights_list.length; j++) {
                                    if (rights_list[j]) {
                                        var right = rights_list[j].trim();
                                        if (right && right.length > 0) {
                                            member['rights'].push({'right':right});
                                        };
                                    };
                                };
                                values['members'].push(member);
                            };
                        };
                    };

                    for (var i = 0; i < server.related('templates').length; i++) {
                        var template = server.related('templates').at(i);
                        var dest = path.join(server.get('template_path'),template.get('destination'));
                        buildTemplate(values, dest, template);
                    };
                };
            };
        });
};
